package net.huashitong.Indicators.service;

import com.alibaba.fastjson.JSONArray;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Indicators.entity.IndicatorBreakdown;
import net.huashitong.Indicators.utils.WorkbookUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static net.huashitong.Indicators.utils.DateForIndUtils.getMonth;

@Service
public class ImportDataService {

    private static final String COL_INDCODE = "指标编码";
    private static final String COL_INDNAME = "指标名称";
    private static final String COL_INDDATE = "指标时间";
    private static final String COL_CUMULATIVE = "累计值";
    private static final String COL_RATIO = "增长";
    private static final String COL_AREA = "地区";
    private static final String COL_EXP_TAG = "（快报）预期目标";    //（快报）预期目标
    private static final String COL_ACC_TAG = "（快报）占预期目标";    //（快报）占预期目标

    private static final String[] lables = {"指标编码", "指标名称",
            "指标时间", "累计值", "增长", "地区",
            "（快报）预期目标", "（快报）预期目标"};

    public List<IndicatorBreakdown> importIndicators(String filePath) throws Exception {
        List<IndicatorBreakdown> result = new ArrayList<>();
        List<String> errors = new ArrayList<>();
        Workbook book = WorkbookUtil.getWorkbook(filePath);
        Sheet sheet = book.getSheetAt(0);
        Iterator<Cell> it = sheet.getRow(0).cellIterator();
        int length = 0;
        List<String> lableList = new ArrayList<>();
        while (it.hasNext()) {
            lableList.add(it.next().getStringCellValue());
            if (length > 8) {
                throw new Exception("模板不正确，请先下载模板");
            }
            length++;
        }
        if (!arrayEquals(lableList.toArray(), lables)) {
            throw new Exception("模板不正确，请先下载模板");
        }
        for (int rowIdx = 1; rowIdx <= sheet.getLastRowNum(); rowIdx++) {
            Row row = sheet.getRow(rowIdx);
            if (WorkbookUtil.isRowEmpty(row)) {
                continue;
            }
            try {
                IndicatorBreakdown indicatorBreakdown = new IndicatorBreakdown();
                //指标编码
                String industryId = WorkbookUtil.getStringCellValue(row, COL_INDCODE);
                if (StringUtils.isBlank(industryId)) {
                    throw new Exception("指标编码不能为空");
                } else {
                    indicatorBreakdown.setIndustryId(industryId);
                }
                //指标名称
                String industryName = WorkbookUtil.getStringCellValue(row, COL_INDNAME);
                if (StringUtils.isBlank(industryName)) {
                    throw new Exception("指标名称不能为空");
                } else {
                    indicatorBreakdown.setIndustryName(industryName);
                }
                //指标时间
                String currentMonth = WorkbookUtil.getStringCellValue(row, COL_INDDATE);
                if (StringUtils.isBlank(currentMonth)) {
                    throw new Exception("指标时间不能为空");
                } else {
                    indicatorBreakdown.setCurrentMonth(currentMonth);
                    String date = getMonth(currentMonth);
                    indicatorBreakdown.setDate(date);
                }
                //累计值
                String cumulative = WorkbookUtil.getStringCellValue(row, COL_CUMULATIVE);
                if (StringUtils.isBlank(cumulative)) {
                    throw new Exception("累计值不能为空");
                } else {
                    indicatorBreakdown.setCumulative(cumulative);
                }
                //增长
                String ratio = WorkbookUtil.getStringCellValue(row, COL_RATIO);
                if (StringUtils.isBlank(ratio)) {
                    throw new Exception("增长不能为空");
                } else {
                    indicatorBreakdown.setRatio(ratio);
                }
                //地区
                String area = WorkbookUtil.getStringCellValue(row, COL_AREA);
                if (StringUtils.isBlank(area)) {
                    throw new Exception("地区不能为空");
                } else {
                    indicatorBreakdown.setArea(area);
                }
                //（快报）预期目标
                String expectedTarget = WorkbookUtil.getStringCellValue(row, COL_EXP_TAG);
                indicatorBreakdown.setExpectedTarget(expectedTarget);

                //（快报）占预期目标
                String accountTarget = WorkbookUtil.getStringCellValue(row, COL_ACC_TAG);
                indicatorBreakdown.setAccountTarget(accountTarget);

                result.add(indicatorBreakdown);

            } catch (Exception e) {
                errors.add("第" + rowIdx + "行：" + e.getMessage());
            }
        }
        if (errors.isEmpty() == false)
            throw new Exception(JSONArray.toJSONString(errors));
        return result;
    }


    /**
     * 判断两个数组是否相同
     *
     * @param a
     * @param b
     * @return
     */
    public static boolean arrayEquals(Object[] a, Object[] b) {
        for (int i = 0; i != (a.length < b.length ? a.length : b.length); i++)
            if (!a[i].equals(b[i])) return false;
        return true;
    }
}
